package com.student.management.root.web;

import com.student.management.root.bean.Menu;
import com.student.management.root.bean.Role;
import com.student.management.root.service.MenuService;
import com.student.management.root.service.RoleService;
import com.student.management.root.service.impl.MenuServiceImpl;
import com.student.management.root.service.impl.MiddleServiceImpl;
import com.student.management.root.service.impl.RoleServiceImpl;
import com.student.management.root.utils.PageUtil;
import com.student.management.root.utils.RoleEnum;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

@WebServlet(urlPatterns = {"/power/role/roles"})
public class RoleServlet extends HttpServlet {
  private RoleService roleService = new RoleServiceImpl();
  private MenuService menuService = new MenuServiceImpl();
  private MiddleServiceImpl middleService = new MiddleServiceImpl();

  @Override
  protected void service(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    System.out.println("开始执行角色管理");
    req.setCharacterEncoding("utf-8");
    String method = req.getParameter("method");
    if ("select".equals(method)) {
      select(req, resp);
    } else if ("selectmenus".equals(method)) {
      selectmenus(req, resp);
    } else if ("insert".equals(method)) {
      insert(req, resp);
    } else if ("update".equals(method)) {
      update(req, resp);
    } else if ("findbyid".equals(method)) {
      findbyid(req, resp);
    } else if ("delete".equals(method)) {
      delete(req, resp);
    } else if ("findInfo".equals(method)) {
      info(req, resp);
    } else if ("enableRole".equals(method)) {
        enableRole(req, resp);
    }else {
      select(req, resp);
    }
  }

    private void enableRole(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String roleid = req.getParameter("roleid");
        int i = roleService.enableRole(Integer.valueOf(roleid));
        PrintWriter writer = resp.getWriter();
        if (i > 0) {
            writer.print(
                    "<script>alert('Enable success');location.href='/4StudentManagement/power/role/roles';</script>");
        } else {
            writer.print(
                    "<script>alert('Enable failed');location.href='/4StudentManagement/power/role/roles';</script>");
        }
    }

    private void info(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
      String roleid = req.getParameter("roleid");
      String method = req.getParameter("method");
//      System.out.println("method: " + method);
//      System.out.println("roleid: " + roleid);
      // 根据主键查询role信息
      RoleServiceImpl roleService = new RoleServiceImpl();
      Role findbyid = roleService.findbyid(Integer.valueOf(roleid));
      System.out.println("要修改的原role信息： " + findbyid.toString());
      ArrayList<Integer> menus = middleService.queryMiddleById(Integer.valueOf(roleid));
//      for (Integer integer : menus) {
//          System.out.println("菜单列表：" + integer.toString());
//      }
      if (menus.contains(1)) {
          req.setAttribute("jiaowu", true);
      } else {
          req.setAttribute("jiaowu", false);
      }
      if (menus.contains(2)) {
          req.setAttribute("quanxian", true);
      } else {
          req.setAttribute("quanxian", false);
      }
      if (menus.contains(3)) {
          req.setAttribute("xuesheng", true);
      } else {
          req.setAttribute("xuesheng", false);
      }
      if (menus.contains(4)) {
          req.setAttribute("yonghu", true);
      } else {
          req.setAttribute("yonghu", false);
      }
      if (menus.contains(5)) {
          req.setAttribute("juese", true);
      } else {
          req.setAttribute("juese", false);
      }
      if (menus.contains(6)) {
          req.setAttribute("caidan", true);
      } else {
          req.setAttribute("caidan", false);
      }

      req.setAttribute("role", findbyid);
      req.getRequestDispatcher("info.jsp").forward(req, resp);
  }

  private void delete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String roleid = req.getParameter("roleid");
    int delete = roleService.delete(Integer.valueOf(roleid));
    PrintWriter writer = resp.getWriter();
    if (delete > 0) {
      writer.print(
          "<script>alert('Delete success');location.href='/4StudentManagement/power/role/roles';</script>");
    } else {
      writer.print(
          "<script>alert('Delete failed');location.href='/4StudentManagement/power/role/roles';</script>");
    }
  }

  private void findbyid(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    String roleid = req.getParameter("roleid");
    String method = req.getParameter("method");
    System.out.println("method: " + method);
    System.out.println("roleid: " + roleid);
    // 根据主键查询role信息
    RoleServiceImpl roleService = new RoleServiceImpl();
    Role findbyid = roleService.findbyid(Integer.valueOf(roleid));
    System.out.println("要修改的原role信息： " + findbyid.toString());
    ArrayList<Integer> menus = middleService.queryMiddleById(Integer.valueOf(roleid));
    for (Integer integer : menus) {
      System.out.println("菜单列表：" + integer.toString());
    }
    if (menus.contains(1)) {
      req.setAttribute("jiaowu", true);
    } else {
      req.setAttribute("jiaowu", false);
    }
    if (menus.contains(2)) {
      req.setAttribute("quanxian", true);
    } else {
      req.setAttribute("quanxian", false);
    }
    if (menus.contains(3)) {
      req.setAttribute("xuesheng", true);
    } else {
      req.setAttribute("xuesheng", false);
    }
    if (menus.contains(4)) {
      req.setAttribute("yonghu", true);
    } else {
      req.setAttribute("yonghu", false);
    }
    if (menus.contains(5)) {
      req.setAttribute("juese", true);
    } else {
      req.setAttribute("juese", false);
    }
    if (menus.contains(6)) {
      req.setAttribute("caidan", true);
    } else {
      req.setAttribute("caidan", false);
    }

    req.setAttribute("role", findbyid);
    req.getRequestDispatcher("edit.jsp").forward(req, resp);
  }

  private void update(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String roleId = req.getParameter("roleid");
    String rolename = req.getParameter("rolename");
    String[] menu = req.getParameterValues("menu");
    String state = req.getParameter("state");
    List mulist = new ArrayList<String>();
    for (String mu : menu) {
      if (RoleEnum.EDUCATIONAL_ADMINISTRATIONCENTER.value.equals(mu)) {
        mulist.add(RoleEnum.EDUCATIONAL_ADMINISTRATIONCENTER.type.toString());
      } else if (RoleEnum.AUTHORITY_MANAGEMENT.value.equals(mu)) {
        mulist.add(RoleEnum.AUTHORITY_MANAGEMENT.type.toString());
      } else if (RoleEnum.STUDENT_MANAGEMENT.value.equals(mu)) {
        mulist.add(RoleEnum.STUDENT_MANAGEMENT.type.toString());
      } else if (RoleEnum.ROLE_MANAGEMENT.value.equals(mu)) {
        mulist.add(RoleEnum.ROLE_MANAGEMENT.type.toString());
      } else if (RoleEnum.USER_MANAGEMENT.value.equals(mu)) {
        mulist.add(RoleEnum.USER_MANAGEMENT.type.toString());
      } else if (RoleEnum.MENU_MANAGEMENT.value.equals(mu)) {
        mulist.add(RoleEnum.MENU_MANAGEMENT.type.toString());
      }
    }
    Role role = new Role();
    role.setRoleid(Integer.valueOf(roleId));
    role.setRolename(rolename);
    role.setRolestate(Integer.valueOf(state));
    role.setMenuList(mulist);
    System.out.println(role.getMenuList().toString());

    String[] ids = (String[]) mulist.toArray(new String[0]);
    for (String s : ids) {
      System.out.println(s);
    }

    int i = roleService.updateById(role, ids);
    PrintWriter printWriter = resp.getWriter();
    if (i > 0) {
      printWriter.print(
          "<script>alert('Update success');location.href='/4StudentManagement/power/role/roles';</script>");
    } else {
      printWriter.print(
          "<script>alert('Update failed');location.href='/4StudentManagement/power/role/roles';</script>");
    }
  }

  // 新增角色
  protected void insert(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    String rolename = req.getParameter("rolename");
    String state = req.getParameter("state");
    String[] menuids = req.getParameterValues("menuid");
    int i = roleService.insertRole(rolename, state, menuids);
    PrintWriter printWriter = resp.getWriter();
    if (i > 0) {
      printWriter.print(
          "<script>alert('Add success');location.href='/4StudentManagement/power/role/roles';</script>");
    } else {
      printWriter.print(
          "<script>alert('Add failed');location.href='/4StudentManagement/power/role/roles';</script>");
    }
  }
  // 查询菜单列表
  protected void selectmenus(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    // 1.接收参数
    // 2.调取service方法
    List<Menu> menuList = menuService.getMenuList();
    req.setAttribute("menulist", menuList);
    req.getRequestDispatcher("add.jsp").forward(req, resp);
  }

  // 查询数据（分页）
  protected void select(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    // 1.接收参数(分页参数+模糊查参数)
    String index = req.getParameter("index");
    int pageIndex = (index == null || index.length() == 0) ? 1 : Integer.parseInt(index);
    // 2.调取service方法(1.查询数据列表的方法  2.查询总条数的方法)
    PageUtil pageUtil = new PageUtil();
    List<Role> roleList = roleService.getRoleList(pageIndex, pageUtil.getPageSize());
    int total = roleService.total();
    pageUtil.setTotal(total);
    pageUtil.setPageIndex(pageIndex);
    pageUtil.setDataList(roleList);

    // 3.存值跳页面
    req.setAttribute("pi", pageUtil);
    req.getRequestDispatcher("list.jsp").forward(req, resp);
  }
}
